
import {
  getCaptchaId
} from '@/api/common'
import store from '@/store'
export default {
  data() {
    return {
      captchaId: '',
      ypOptions: null,
      ypDom: null,
      captchaToken: '',
      authenticate: ''
    }
  },
  methods: {
    /**
     * 第三方的防刷校验
     */
    createYpRiddler(options, mobile) {
      const _this = this
      _this.ypOptions = {
        appId: '',
        version: 'v1',
        lang: 'zh-cn',
        container: '',
        winWidth: '300',
        noButton: false,
        beforeStart: (next) => {
          console.log('验证马上开始')
          next()
        },
        onSuccess: async(validInfo, close) => {
          console.log('验证成功')
          this.$message({
            message: '恭喜你，验证成功',
            type: 'success'
          })
          _this.captchaToken = validInfo.token
          _this.authenticate = validInfo.authenticate
          // if (mobile !== '') {
          //   _this.getCode(mobile)
          // }
          console.log(`验证通过!token=${validInfo.token}, authenticate=${validInfo.authenticate}`)
          // 请求上报接口
          close()
        },
        onError: (param) => {
          console.log('验证报错', param)
          if (param.code === 429) {
            this.$message.error('请求过于频繁，请稍后再试！')
          }
        },
        onFail: (code, msg, retry) => {
          // this.$message.error('验证失败')
          // this.$toast('出错啦：' + msg + ' code: ' + code)
          retry()
        },
        onExit: () => {
          console.log('退出验证')
        }
      }
      _this.ypOptions = Object.assign(_this.ypOptions, options)
      try {
        // eslint-disable-next-line
        _this.ypDom = new YpRiddler(_this.ypOptions)
      } catch (error) {
        console.log(error)
      }
    },
    handlerGetCaptchaId(ypRiddlerDom) {
      return getCaptchaId({
        token: store.getters.token
      }).then(res => {
        const result = res.data
        console.log(result.captchaId, 'rsee')
        this.captchaId = result.captchaId
        // this.createYpRiddler({
        //   appId: this.captchaId,
        //   container: ypRiddlerDom
        // })
      })
    },
    async handlerTriggerValidate(ypRiddlerDom, mobile) {
      // 创建人机验证弹窗
      if (!this.ypDom) {
        // 调用获取创建人机验证appId接口
        await this.handlerGetCaptchaId()
        this.createYpRiddler({
          appId: this.captchaId,
          container: ypRiddlerDom
        }, mobile)
      }
      // 触发人机验证
      // ypRiddlerDom.click()
    }
  }
}
